package com.zlzlib.loadtest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.pluginmgr.PluginManager;
import androidx.pluginmgr.environment.PlugInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @Desc:
 * @Copyright:
 * @DateTime: 2022/10/27 16:36
 * @Author zlz
 * @Version 1.0
 */
public class LoadMainActivity extends Activity {

    private List<PlugInfo> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_main);
        PluginManager.init(getApplicationContext());
        PluginManager.getSingleton().setActivitySelector(TestActivitySelector.getDefault());
    }

    public void loadClick(View view) {
        new Thread(() -> {
            try {
                Collection<PlugInfo> collection = PluginManager.getSingleton().loadPlugin(getExternalFilesDir("apk"));
                list = new ArrayList<>(collection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void jumpClick1(View view) {
        if (list == null || list.isEmpty()) {
            return;
        }
        Log.i(this.getClass().getName(), list.get(0).getFilePath() + " -- " + list.get(0).getDexFile());
        PluginManager.getSingleton().startMainActivity(this, list.get(0));
    }

    public void delete1(View view) {
        installApk(new File(getExternalFilesDir("apk"),"PdaHuaxi.apk"), this);
    }

    public void jumpClick2(View view) {
        if (list == null || list.size() < 2) {
            return;
        }
        PluginManager.getSingleton().startMainActivity(this, list.get(1));
    }

    public void delete2(View view) {
        PluginManager.getSingleton().uninstallPluginByPkg(list.get(1).getPackageName(), true);
    }

    public static void installApk(File file, Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.putExtra("isPluginStart", false);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
//        PluginManager.getSingleton().startActivity();
    }
}
